package com.runen.infinitemovement.activity;

import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.annotation.Nullable;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.runen.infinitemovement.R;
import com.runen.infinitemovement.adapter.treeview.LayoutItem;
import com.runen.infinitemovement.adapter.treeview.TreeNode;
import com.runen.infinitemovement.adapter.treeview.TreeViewAdapter;
import com.runen.infinitemovement.adapter.treeview.TreeViewBinder;
import com.runen.infinitemovement.base.BaseActivity;
import com.runen.infinitemovement.model.api.CompanyAPI;
import com.runen.infinitemovement.model.api.UserAPI;
import com.runen.infinitemovement.model.base.BaseResponseEntity;
import com.runen.infinitemovement.model.entity.EventBusEntity;
import com.runen.infinitemovement.model.entity.NextAllCompanyStructureEntity;
import com.runen.infinitemovement.model.entity.TopCompanyEntity;
import com.runen.infinitemovement.treenode.BranchNode;
import com.runen.infinitemovement.treenode.BranchViewBinder;
import com.runen.infinitemovement.treenode.LeafNode;
import com.runen.infinitemovement.treenode.LeafNode2;
import com.runen.infinitemovement.treenode.LeafNode3;
import com.runen.infinitemovement.treenode.LeafViewBinder;
import com.runen.infinitemovement.treenode.LeafViewBinder2;
import com.runen.infinitemovement.treenode.LeafViewBinder3;
import com.runen.infinitemovement.treenode.RootNode;
import com.runen.infinitemovement.treenode.RootViewBinder;
import com.runen.infinitemovement.widget.popupwind.AddCorpsPoppupWindow;
import com.runen.rxnetlibrary.net.callback.BaseResultCallback;
import com.runen.rxnetlibrary.utils.LogUtil;
import com.runen.rxnetlibrary.utils.ToastUtils;

import org.greenrobot.eventbus.EventBus;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class CheckBranchActivity extends BaseActivity {

    @BindView(R.id.top_btn_left)
    Button topBtnLeft;
    @BindView(R.id.top_title)
    TextView topTitle;
    @BindView(R.id.rv_check_branch)
    RecyclerView rvCheckBranch;
    @BindView(R.id.top_btn_right)
    Button topBtnRight;
    @BindView(R.id.top_tv_right)
    TextView topTvRight;
    @BindView(R.id.top_iv_right)
    ImageView topIvRight;
    @BindView(R.id.ll_title)
    LinearLayout llTitle;
    @BindView(R.id.tv_checked_name)
    TextView tvCheckedName;
    @BindView(R.id.tv_sure)
    TextView tvSure;
    @BindView(R.id.ll_bottom)
    LinearLayout llBottom;
    private List<TreeNode> list = new ArrayList<>();
    private TreeViewAdapter adapter;
    private String checkName;
    private String checkId;
    private int changeBranch;
    private String lastId;
    private String leader;
    private String branchNodeId;

    @Override
    protected int getLayoutId() {
        return R.layout.activity_check_branch;
    }

    @Override
    protected void initView(@Nullable Bundle savedInstanceState) {
        ButterKnife.bind(this);
        changeBranch = getIntent().getIntExtra("changeBranch", 0);
        if (changeBranch == 1) {
            topBtnLeft.setVisibility(View.VISIBLE);
        } else {
            topBtnLeft.setVisibility(View.INVISIBLE);
        }
        topTitle.setText("选择企业军团");
        LinearLayoutManager layoutManager = new LinearLayoutManager(this);
        layoutManager.setOrientation(RecyclerView.VERTICAL);
        rvCheckBranch.setLayoutManager(layoutManager);
        initAdapter();
        initData();
    }

    private void initData() {
        new UserAPI().getTopCompany("", new BaseResultCallback<TopCompanyEntity>() {
            @Override
            public void onResponse(TopCompanyEntity response) {
                if (response.code == 0) {
                    List<TreeNode> rootList = new ArrayList<>();
                    if (response.data != null) {
                        if (response.data.size() > 0) {
                            for (int i = 0; i < response.data.size(); i++) {
                                TreeNode<RootNode> node = new TreeNode<>(new RootNode(response.data.get(i).name,
                                        response.data.get(i).id, response.data.get(i).leader));
                                rootList.add(node);
                            }
                        }
                    }
                    list.clear();
                    list.addAll(rootList);
                    adapter.notifyData(list);
                } else {
                    ToastUtils.showShort(response.msg);
                }

            }
        });

    }

    private String topCheckId;
    private TreeNode treeNodeItem;

    private void initAdapter() {
        adapter = new TreeViewAdapter(list, Arrays.asList(new RootViewBinder(), new BranchViewBinder(),
                new LeafViewBinder(), new LeafViewBinder2(), new LeafViewBinder3())) {
            @Override
            public void toggleClick(TreeViewBinder.ViewHolder viewHolder, View view, boolean isOpen, TreeNode treeNode) {
                LogUtil.e("checkName", viewHolder.getAdapterPosition() + "");
                adapter.setCheck(viewHolder.getAdapterPosition());
                treeNodeItem = treeNode;
                viewHolder.findViewById(R.id.ivNode).setRotation(isOpen ? 90 : 0);
                LayoutItem item = treeNode.getValue();
                if (item instanceof RootNode) {
                    checkName = ((RootNode) item).getName();
                    checkId = ((RootNode) item).getId();
                    topCheckId = ((RootNode) item).getId();
                    lastId = ((RootNode) item).getId();
                    leader = ((RootNode) item).getLeader();
                    branchNodeId = ((RootNode) item).getId();
                } else if (item instanceof BranchNode) {
                    if (((BranchNode) item).getName().equals("添加")) {
                        showPupop();
                    } else {
                        lastId = ((BranchNode) item).getId();
                        leader = ((BranchNode) item).getLeader();
                        checkName = checkName + ((BranchNode) item).getName();
                        checkId = ((BranchNode) item).getId();
                    }

                } else if (item instanceof LeafNode) {
                    if (((LeafNode) item).getName().equals("添加")) {
                        showPupop();
                    } else {
                        lastId = ((LeafNode) item).getId();
                        leader = ((LeafNode) item).getLeader();
                        checkName = checkName + ((LeafNode) item).getName();
                        checkId = ((LeafNode) item).getId();
                    }

                } else if (item instanceof LeafNode2) {
                    if (((LeafNode2) item).getName().equals("添加")) {
                        showPupop();
                    } else {
                        lastId = ((LeafNode2) item).getId();
                        leader = ((LeafNode2) item).getLeader();
                        checkName = checkName + ((LeafNode2) item).getName();
                        checkId = ((LeafNode2) item).getId();
                    }

                } else if (item instanceof LeafNode3) {
                    checkName = checkName + ((LeafNode3) item).getName();
                    checkId = ((LeafNode3) item).getId();
                }
                tvCheckedName.setText(checkName);
                addNewNode(treeNode);
            }

            @Override
            public void toggled(TreeViewBinder.ViewHolder viewHolder, View view, boolean isOpen, TreeNode treeNode) {

            }

            @Override
            public void checked(TreeViewBinder.ViewHolder viewHolder, View view, boolean checked, TreeNode treeNode) {
            }

            @Override
            public void itemClick(TreeViewBinder.ViewHolder viewHolder, View view, TreeNode treeNode) {
                String name = null;

                adapter.notifyDataSetChanged();
//                adapter.lastToggleClickToggle();
//                Toast.makeText(MainActivity.this, name, Toast.LENGTH_SHORT).show();
            }
        };
        rvCheckBranch.setAdapter(adapter);
    }

    private AddCorpsPoppupWindow poppupWindow;

    private void showPupop() {
        poppupWindow = AddCorpsPoppupWindow.getInstance(this);
        poppupWindow.setOnHozonClickListener(new AddCorpsPoppupWindow.OnHozonClickListener() {
            @Override
            public void onHozomClick(String corpsName) {
                onAddCorps(corpsName);
            }
        });
        poppupWindow.show();

    }

    private void onAddCorps(String corpsName) {
        if (TextUtils.isEmpty(corpsName)) {
            ToastUtils.showShort("请输入新团队名称");
            return;
        }
        JSONObject object = new JSONObject();
        try {
            object.put("parentId", checkId);
            object.put("companyName", corpsName);
            object.put("leader", leader);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        showDialog();
        new CompanyAPI().addNextCorps(object.toString(), new BaseResultCallback<BaseResponseEntity<?>>() {
            @Override
            public void onResponse(BaseResponseEntity<?> response) {
                dismissDialog();
                if (response.getCode() == 0) {
                    if (poppupWindow != null) {
                        poppupWindow.dismiss();
                        ToastUtils.showShort("添加团队成功，请重新选择团队");
                        treeNodeItem.setLoad(false);
                        adapter.setCheck(-1);
                        initData();
                    }
                } else {
                    ToastUtils.showShort(response.getMessage());
                }

            }
        });
    }


    private void addNewNode(final TreeNode treeNode) {
        LogUtil.e("checkName1", "zoule");
        if (treeNode.getValue() instanceof RootNode) {
            RootNode rootNode = (RootNode) treeNode.getValue();
            if (!treeNode.isLoad()) {
                if (!TextUtils.isEmpty(rootNode.getId())) {
                    String str = "?companyId=%s";
                    showDialog();
                    new UserAPI().getNextAllCompany(String.format(str, rootNode.getId()), new BaseResultCallback<NextAllCompanyStructureEntity>() {
                        @Override
                        public void onResponse(NextAllCompanyStructureEntity response) {
                            dismissDialog();
                            TreeNode<BranchNode> branchNodeTreeNodeAfter = new TreeNode<>(new BranchNode("添加", "", ""));
                            if (response.data != null) {
                                if (response.data.size() > 0) {
                                    for (int i = 0; i < response.data.size(); i++) {
                                        TreeNode<BranchNode> branchNodeTreeNode = new TreeNode<>(new BranchNode(response.data.get(i).name,
                                                response.data.get(i).id, response.data.get(i).leader));
                                        TreeNode<LeafNode> leafNodeTreeNodeNull = new TreeNode<>(new LeafNode("添加", "", ""));

                                        if (response.data.get(i).departments != null && response.data.get(i).departments.size() > 0) {
                                            List<NextAllCompanyStructureEntity.DataBean.DepartmentsBean> departments =
                                                    (List<NextAllCompanyStructureEntity.DataBean.DepartmentsBean>) response.data.get(i).departments;
                                            if (departments.size() > 0) {
                                                for (int j = 0; j < departments.size(); j++) {
                                                    TreeNode<LeafNode> leafNodeTreeNode = new TreeNode<>(new LeafNode(departments.get(j).name, departments.get(j).id, departments.get(j).leader));
                                                    TreeNode<LeafNode2> leafNodeTreeNode2Null = new TreeNode<>(new LeafNode2("添加", "", ""));
                                                    if (departments.get(j).departments != null && departments.get(j).departments.size() > 0) {
                                                        List<NextAllCompanyStructureEntity.DataBean.DepartmentsBean.DepartmentsBeanX> departments2 =
                                                                (List<NextAllCompanyStructureEntity.DataBean.DepartmentsBean.DepartmentsBeanX>) departments.get(j).departments;
                                                        for (int k = 0; k < departments2.size(); k++) {
                                                            TreeNode<LeafNode2> leafNodeTreeNode2 = new TreeNode<>(new LeafNode2(departments2.get(k).name, departments2.get(k).id, departments2.get(k).leader));
                                                            if (departments2.get(k).departments != null) {
                                                                List<NextAllCompanyStructureEntity.DataBean.DepartmentsBean.DepartmentsBeanX.DepartmentsBeanXX> departments3 =
                                                                        (List<NextAllCompanyStructureEntity.DataBean.DepartmentsBean.DepartmentsBeanX.DepartmentsBeanXX>) departments2.get(k).departments;
                                                                for (int l = 0; l < departments3.size(); l++) {
                                                                    TreeNode<LeafNode3> leafNodeTreeNode3 = new TreeNode<>(new LeafNode3(departments3.get(l).name, departments3.get(l).id));
                                                                    leafNodeTreeNode2.addChild(leafNodeTreeNode3);
                                                                }
                                                            }
                                                            leafNodeTreeNode.addChild(leafNodeTreeNode2);
                                                        }
                                                    }
                                                    leafNodeTreeNode.addChild(leafNodeTreeNode2Null);
                                                    branchNodeTreeNode.addChild(leafNodeTreeNode);
                                                }
                                            }
                                        }
                                        branchNodeTreeNode.addChild(leafNodeTreeNodeNull);
                                        treeNode.addChild(branchNodeTreeNode);
                                    }
                                }
                            }
                            treeNode.addChild(branchNodeTreeNodeAfter);
                            treeNode.setLoad(true);
                            adapter.lastToggleClickToggle();
                        }
                    });
                }
            } else {
                adapter.lastToggleClickToggle();
            }
        } else {
            adapter.lastToggleClickToggle();
        }
    }

    @OnClick(R.id.tv_sure)
    public void onViewClicked() {

    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // TODO: add setContentView(...) invocation
        ButterKnife.bind(this);
    }

    @OnClick({R.id.top_btn_left, R.id.tv_sure})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.top_btn_left:
                finish();
                break;
            case R.id.tv_sure:
                if (changeBranch == 1) {
                    onSure();
                } else {
                    Intent intent = new Intent();
                    intent.putExtra("BRANCH_NAME", checkName);
                    intent.putExtra("BRANCH_ID", checkId);
                    intent.putExtra("BRANCH_TOP_ID", topCheckId);
                    setResult(99, intent);
                    finish();
                }
                break;
        }
    }

    private void onSure() {
        JSONObject object = new JSONObject();
        try {
            object.put("tenantId", checkId);
            object.put("topTenantId", topCheckId);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        showDialog();
        new UserAPI().checkBranch(object.toString(), new BaseResultCallback<BaseResponseEntity<?>>() {
            @Override
            public void onResponse(BaseResponseEntity<?> response) {
                dismissDialog();
                if (response.getCode() == 0) {
                    EventBus.getDefault().post(new EventBusEntity(99));
                    ToastUtils.showShort(response.getMessage());
                    finish();
                } else {
                    ToastUtils.showShort(response.getMessage());
                }
            }
        });
    }
}
